﻿using ExamSelf.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Mvc;

namespace ExamSelf.Web.Controllers
{
    public class LoginController : Controller
    {
       
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            UserRequest request = new UserRequest(HttpContext);
            using (var db = new ExamSelfDbContext())
            {
                var user = db.Users.Where(i => i.LoginName == request.UserName && i.PassWord == request.Password).SingleOrDefault();
                if (user != null)
                {
                    HttpContext.Session.Add("User", user);
                    return Json("true");
                }
                else
                {
                    return Json("false");
                }
            }
        } 


        public class RequiresAuthenticationAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (filterContext.HttpContext.Session["User"] == null)
                {
                    filterContext.HttpContext.Response.Redirect("/Login/Index", true);
                }
                //if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                //{
                //    string returnUrl = filterContext.HttpContext.Request.Url.AbsolutePath;
                //    string redirectUrl = string.Format("?ReturnUrl={0}", returnUrl);
                //    //string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                //    //filterContext.HttpContext.Response.Redirect(loginUrl, true);
                //}
            }
        }  
    }

}